package com.baidu.service.impl;
import com.baidu.entity.Borr;
import com.baidu.entity.Sked;
import com.baidu.entity.TbyRegister;
import com.baidu.entity.WycRepayment;
import com.baidu.fegin.MessageFegin;
import com.baidu.mapper.BorrMapper;
import com.baidu.mapper.SkedMapper;
import com.baidu.mapper.TbyRegisterMapper;
import com.baidu.mapper.WycRepaymentMapper;
import com.baidu.service.OverdueService;
import com.baidu.utils.ResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @Description: 还款实现类
 * @Author: 王雨超
 * @Date: 2021/12/11 13:38
 */
@Service
@Transactional
@Slf4j
@SuppressWarnings({"all"})
public class OverdueServiceImpl implements OverdueService {
    @Autowired
    private  OverdueServiceImpl overdueService;
    @Autowired
    private BorrMapper borrMapper;
    @Autowired
    private SkedMapper skedMapper;
    @Autowired
    private WycRepaymentMapper wycRepaymentMapper;
    @Autowired
    private MessageFegin messageFegin;
    @Autowired
    private TbyRegisterMapper tbyRegisterMapper;
    @Override
    public List<Sked> findBorr(int userid) {
        //通过用户id查询出借款记录
        List<Borr> userid1 = borrMapper.selectList(new QueryWrapper<Borr>().eq("userid", userid));
        for (Borr borr : userid1) {
            //判断是未还款的记录
            if(borr.getEmptys()==0){
                //查询还款计划
                List<Sked> bid = skedMapper.selectList(new QueryWrapper<Sked>().eq("bid", borr.getBid()));
                log.info("{}",bid);
                return bid;
            }
        }
        return null;
    }
    /**
    *@Description: 查看提前还款金额方法
    *@Author: 王雨超
    *@Date: 2021/12/16
    *@Param: 用户id
    *@return: Double 类型的 money
    */
    @Override
    public Double findMoney(int userid) {
        return  overdueService.findsum(userid);
    }
    /**
    *@Description: 提前全部还款方法
    *@Author: 王雨超
    *@Date: 2021/12/20
    *@Param: 用户id  还款金额
    *@return:  ResultResponse
    */
    @Transactional
    @Override
    public ResultResponse prepayment(int userid, double money) {
        double money1=0.0d;
        Double findsum = this.overdueService.findsum(userid);
        if(findsum==money){
            List<Borr> userid1 = borrMapper.selectList(new QueryWrapper<Borr>().eq("userid", userid));
            for (Borr borr : userid1) {
                if(borr.getEmptys()==0){
                    //修改状态，1已还完
                    borr.setEmptys(1);
                    borrMapper.updateById(borr);
                    List<Sked> bid = skedMapper.selectList(new QueryWrapper<Sked>().eq("bid", borr.getBid()));
                    for (Sked sked : bid) {
                        money1+=sked.getInterest();
                        sked.setWon(1);
                        skedMapper.updateById(sked);
                    }
                }
            }
            //记录在数据库
            WycRepayment wycRepayment = new WycRepayment();
            wycRepayment.setUid(userid);
            wycRepayment.setCreateTime(new Date());
            wycRepayment.setPrincipal(money);
            wycRepayment.setType(1);
            wycRepayment.setInterest(money1);
            wycRepayment.setPeriods(0);
            wycRepaymentMapper.insert(wycRepayment);
            TbyRegister tbyRegister = tbyRegisterMapper.selectById(userid);
            ResultResponse resultResponse = this.sendMessage("2", "提前还款成功！", userid + "", tbyRegister.getIphone());
            log.info("{}发送短信",resultResponse);
            return ResultResponse.SUCCESS();
        }else{
            return ResultResponse.FAILED("输入金额有误");
        }
    }
    /**
    *@Description: 按期还款的金额
    *@Author: 王雨超
    *@Date: 2021/12/20
    *@Param: 用户id   userid  期数 wvs
    *@return: 应还金额
    */
    @Override
    public Double scheduleMoney(int userid, int wvs) {
        List<Borr> userid1 = borrMapper.selectList(new QueryWrapper<Borr>().eq("userid", userid));
        for (Borr borr : userid1) {
            List<Sked> bid = skedMapper.selectList(new QueryWrapper<Sked>().eq("bid", borr.getBid()));
            for (Sked sked : bid) {
                if(sked.getWvs()==wvs){
                    return sked.getNums();
                }
            }
        }
        return null;
    }
    /**
    *@Description: 按期还款
    *@Author: 王雨超
    *@Date: 2021/12/20
    *@Param: map{userid wvs money}
    *@return: ResultResponse
    */
    @Override
    public ResultResponse schedule(Map<String,String> map) {
        List<Borr> borrs = borrMapper.selectList(new QueryWrapper<Borr>().eq("userid", map.get("userid")));
        for (Borr borr : borrs) {
            List<Sked> bid = skedMapper.selectList(new QueryWrapper<Sked>().eq("bid", borr.getBid()));
            for (Sked sked : bid) {
                if (sked.getWon() == 0) {
                    if (sked.getWvs() == Integer.parseInt(map.get("wvs"))) {
                        if (new BigDecimal(sked.getNums()).longValue() == new BigDecimal(Double.parseDouble(map.get("money"))).longValue()) {
                            //修改状态
                            sked.setWon(1);
                            skedMapper.updateById(sked);
                            //修改借款表
                            Borr borr1 = borrMapper.selectById(sked.getBid());
                            borr1.setNid(borr1.getNid() - 1);
                            borrMapper.updateById(borr1);
                            Borr borr2 = borrMapper.selectById(sked.getBid());
                            if (borr2.getNid() == 0) {
                                borr2.setEmptys(1);
                                borrMapper.updateById(borr2);
                            }
                            //添加到数据库
                            WycRepayment wycRepayment = new WycRepayment();
                            wycRepayment.setUid(borr.getUserid());
                            wycRepayment.setCreateTime(new Date());
                            wycRepayment.setPrincipal(sked.getPrincipal());
                            wycRepayment.setType(2);
                            wycRepayment.setInterest(sked.getInterest());
                            wycRepayment.setPeriods(borr2.getNid());
                            wycRepaymentMapper.insert(wycRepayment);
                            String phone = this.findPhone(borr.getUserid());
                            ResultResponse resultResponse = this.sendMessage("2", "按期还款成功！", borr.getUserid() + "", phone);
                            log.info("{}按期还款发送短信！",resultResponse);
                            return ResultResponse.SUCCESS();
                        } else {
                            return ResultResponse.FAILED("金额有误！");
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
    *@Description: 查询用户借款金额
    *@Author: 王雨超
    *@Date: 2021/12/20
    *@Param:  用户id
    *@return: 金额 money
    */
    public Double findsum(Integer userid){
        double money=0.0d;
        if(userid!=null){
            //调用还款计划数据 计算出应还金额
            List<Borr> userid1 = borrMapper.selectList(new QueryWrapper<Borr>().eq("userid", userid));
            for (Borr borr : userid1) {
                //判断是未还款的记录
                if(borr.getEmptys()==0){
                    //查询还款计划
                    List<Sked> bid = skedMapper.selectList(new QueryWrapper<Sked>().eq("bid", borr.getBid()));
                    for (Sked sked : bid) {
                        money+=sked.getNums();
                    }
                }
            }
        }
        return money;
    }
    /**
    *@Description: 使用fegin调用发送短信
    *@Author: 王雨超
    *@Date: 2021/12/23
    *@Param: code message uid phone
    *@return: ResultResponse
    */
    public ResultResponse sendMessage(String code,String message,String uid,String phone){
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        map.put("message",message);
        map.put("uid",uid);
        map.put("phone",phone);
        ResultResponse resultResponse = messageFegin.sendMessage(map);
        return resultResponse;
    }
    /**
    *@Description: 查询用户借款记录
    *@Author: 王雨超
    *@Date: 2021/12/23
    *@Param: userid
    *@return: List<Borr>
    */
    @Override
    public List<Borr> findBorrList(int userid) {
        return borrMapper.selectList(new QueryWrapper<Borr>().eq("userid",userid));
    }
    /**
    *@Description: 查询提前还款应还金额
    *@Author: 王雨超
    *@Date: 2021/12/23
    *@Param: bid 借款记录主键
    *@return: Double
    */
    @Override
    public Double findNums(int bid) {
        double money=0.0d;
        List<Sked> skeds = skedMapper.selectList(new QueryWrapper<Sked>().eq("bid", bid));
        for (Sked sked : skeds) {
            money+=sked.getNums();
        }
        return money;
    }
    /**
    *@Description: 提前还款方法
    *@Author: 王雨超
    *@Date: 2021/12/23
    *@Param:  bid借款记录主键  money金额  用户id
    *@return: ResultResponse
    */
    @Override
    public ResultResponse advance(int bid, Double money,int userid) {
        Double nums = this.findNums(bid);
        if(new BigDecimal(nums).longValue()==new BigDecimal(money).longValue()){
            Borr borr = new Borr();
            borr.setBid(bid);
            borr.setEmptys(1);
            borrMapper.updateById(borr);
            List<Sked> skeds = skedMapper.selectList(new QueryWrapper<Sked>().eq("bid", bid));
            for (Sked sked : skeds) {
                sked.setWon(1);
                skedMapper.updateById(sked);
            }
            //记录在数据库
            WycRepayment wycRepayment = new WycRepayment();
            wycRepayment.setUid(userid);
            wycRepayment.setCreateTime(new Date());
            wycRepayment.setPrincipal(money);
            wycRepayment.setType(1);
            wycRepayment.setInterest(nums);
            wycRepayment.setPeriods(0);
            wycRepaymentMapper.insert(wycRepayment);
            String phone = this.findPhone(userid);
            ResultResponse resultResponse = this.sendMessage("2", "提前还款成功！", userid + "", phone);
            log.info("{}短信发送成功",resultResponse);
            return ResultResponse.SUCCESS();
        }
        return ResultResponse.FAILED("输入的金额不正确！");
    }
    /**
     *@Description: 最低还款：查询还款计划
     *@Author: 王雨超
     *@Date: 2021/12/24
     *@Param: userid 用户id
     *@return: ResultResponse
     */
    @Override
    public ResultResponse minimum(int userid) {
        List<Sked> borr = this.findBorr(userid);
        if(borr!=null){
            return ResultResponse.SUCCESS(borr);
        }
        return ResultResponse.FAILED("不存在！");
    }
    /**
     *@Description: 最低还款：计算最低还款金额
     *@Author: 王雨超
     *@Date: 2021/12/24
     *@Param: 用户id  userid 期数  wvs
     *@return: ResultResponse
     */
    @Override
    public Double minmoney(int userid, int wvs) {
        double minmoney=0.0d;
        List<Sked> borr = this.findBorr(userid);
        if(borr!=null){
            for (Sked sked : borr) {
                if(sked.getWvs()==wvs){
                    //计算最低还款额
                    minmoney=sked.getNums()*0.1;
                }
            }
            return minmoney;
        }
        return null;
    }
    /**
    *@Description: 最低还款
    *@Author: 王雨超
    *@Date: 2021/12/24
    *@Param: 用户id  userid 期数  wvs 最低还款额 minmoney
    *@return: ResultResponse
    */
    @Override
    public ResultResponse minpayment(int userid, int wvs, double minmoney) {
        double money=0.0d;
        double lixi=0.0d;
        int count=-1;
        //计算出最低还款额
        Double minmoney1 = this.minmoney(userid, wvs);
        if(minmoney1!=null){
            if(minmoney==minmoney1){
                List<Sked> borr = this.findBorr(userid);
                for (Sked sked : borr) {
                    if(sked.getWvs()==wvs){
                        money= sked.getNums()-minmoney;
                        lixi=sked.getInterest();
                    }
                    count++;
                }
                //修改数据库
                for (Sked sked : borr) {
                    if(sked.getWvs()!=wvs){
                        sked.setNums(sked.getNums()+money/2);
                        skedMapper.updateById(sked);
                    }else{
                        sked.setWon(1);
                        skedMapper.updateById(sked);
                        //记录数据库
                        WycRepayment wycRepayment = new WycRepayment();
                        wycRepayment.setUid(userid);
                        wycRepayment.setCreateTime(new Date());
                        wycRepayment.setPrincipal(money);
                        wycRepayment.setType(4);
                        wycRepayment.setInterest(lixi);
                        wycRepayment.setPeriods(count);
                        wycRepaymentMapper.insert(wycRepayment);
                        //短信通知
                        String phone = this.findPhone(userid);
                        ResultResponse resultResponse = this.sendMessage("2", "最低还款成功！", userid + "", phone);
                        log.info("{}短信通知",resultResponse);
                    }
                }
                return ResultResponse.SUCCESS();
            }else{
                return ResultResponse.FAILED("金额不正确！");
            }
        }else{
            return ResultResponse.FAILED("错误！");
        }
    }
    /**
    *@Description: 根据用户id 查询手机号
    *@Author: 王雨超
    *@Date: 2021/12/24
    *@Param: userid
    *@return: phone
    */
    public String findPhone(int userid){
        TbyRegister tbyRegister = tbyRegisterMapper.selectById(userid);
        log.info("{}根据用户id查询手机号",tbyRegister);
        return tbyRegister.getIphone();
    }
}
